import {getToken,setToken,removeToken,setTimeStamp} from '@/utils/auth'

import {loginApi, getUserInfo} from '@/api/user'
import {getEmployees} from '@/api/employees'
import {resetRouter} from '@/router/index'

const state = {
  token:getToken() || '',
  userInfo:{}
}

const mutations = {
  //存token
  SET_TOKEN(state,payload){
    //vuex中设置token
    state.token = payload
    //将token保存到cookies中
    setToken(payload)
    //顺便讲时间戳保存到cookies
    setTimeStamp()
  },
  //移除token
  REMOVE_TOKEN(state){
    state.token = ''
    removeToken()
  },
  //设置用户信息
  GET_INFO(state,payload){
    state.userInfo = payload
  },
  //删除用户信息
  REMOVE_INFO(state){
    state.userInfo = {}
  }
}
const actions = {
  //用户登录
  async login({commit},payload){
    let res = await loginApi(payload)
    console.log(res);
  
    // console.log(photo);
    // let res = {...result,...photo}
    console.log(res);
    commit('SET_TOKEN',res.data)
    // console.log(res.data);
  },
  //获取用户信息
  async getInfo({commit}){
    let result = await getUserInfo()
    let photo = await getEmployees(result.data.userId)
    let res = {...result.data,...photo.data}
    console.log(res);
    commit('GET_INFO', res)
    return res
  },
  //退出登录
  async logout({commit}){
    commit('REMOVE_TOKEN')
    commit('REMOVE_INFO')
    resetRouter()
  }
}

export default{
  namespaced:true,
  state,
  mutations,
  actions
}